package com.november.lottery.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.november.lottery.base.BaseException;
import com.november.lottery.constant.HttpCustomStatusEnum;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局错误处理
 * @author xiang
 */
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public String BaseExceptionHandler(HttpServletRequest request, HttpServletResponse response, BaseException exception) throws Exception {

        response.setStatus(HttpCustomStatusEnum.CODE_DEFINE.value);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(BaseException.class, "message","code","status");
        return JSON.toJSONString(exception,filter);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) throws Exception {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Exception.class, "message");
        return JSON.toJSONString(exception,filter);
    }

}
